import axios from 'axios'
import router from '../router/index.js'
import { message } from 'ant-design-vue'

if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = 'http://localhost:8080'
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = 'http://www.production.cn'
}

// 请求拦截
axios.interceptors.request.use(
  function (config) {
    const token = window.sessionStorage.getItem('token')
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截
axios.interceptors.response.use(
  function (response) {
    if (response.status === 200) {
      return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
  },
  function (error) {
    switch (error.response.status) {
      case 401:
        window.sessionStorage.removeItem('token')
        window.sessionStorage.removeItem('username')
        router.push({ path: '/login' })
        break
      default:
        message.error(error.response.data.message || '未知错误')
    }
    return Promise.reject(error)
  }
)

// 封装get请求
export function get (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: params })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}

// 封装post，put，delete等请求可以接着往下写
